package com.xp.basic.heima.nio.netty.simpledemo.worker;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;

public class TestByteBuf {
    public static void main(String[] args) {

        //byteBuf 自动扩容
        //byteBuf 自动扩容 如果写入的字节小于 512 那么会扩容为 16的倍数
        // 如果大于512 那么扩容会扩容 2的n次方 2^n 次方
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(6);
        System.out.println("buffer = " + buffer);
        buffer.writeBytes("123456".getBytes());
        System.out.println("buffer = " + buffer);
        buffer.writeBytes("abcde".getBytes());
        System.out.println("buffer = " + buffer);




        //slice  对应的是零拷贝
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(10);
        ByteBuf byteBuf1 = byteBuf.writeBytes(new byte[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'});
        System.out.println(byteBuf == byteBuf1);

        ByteBuf slice = byteBuf.slice();
        System.out.println(slice);
        ByteBuf b1 = byteBuf.slice(0, 5);
        //使用 ByteBuf 零拷贝技术一定不能忘了 RETAIN 这个 byteBuf 不然如果原始内存被释放了就有坑
        b1.retain();
        ByteBuf b2 = byteBuf.slice(5, 5);
        b2.retain();

        System.out.println("b1 = " + b1);
        System.out.println("b2 = " + b2);

        System.out.println(" =   = = = =  = = = 释放原始内存  = = = = = = = =  =  ");
        byteBuf.release();

        System.out.println("b1 = " + b1);
        System.out.println("b2 = " + b2);
        b1.release();
        b2.release();
        System.out.println(" =   = = = =  = = = 全部释放原始内存  = = = = = = = =  =  ");

        System.out.println("b1 = " + b1);
        System.out.println("b2 = " + b2);

        // duplicate 也是零拷贝，共同同一块内存，但是读写指针不一致
//        ByteBuf duplicate = byteBuf.duplicate();

        // copy 代表的是全拷贝
//        ByteBuf copied = byteBuf.copy();

        // byteBuf  的 复制整合
        ByteBuf cb1 = ByteBufAllocator.DEFAULT.heapBuffer(2).writeBytes("123".getBytes());

        ByteBuf cb2 = ByteBufAllocator.DEFAULT.heapBuffer(2).writeBytes("456".getBytes());
        CompositeByteBuf compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer();
//        CompositeByteBuf addComponents = compositeByteBuf.addComponents(cb1, cb2);
        //加上 true 代表需要将指针进行统一处理，写指针指针位置实时更新
        CompositeByteBuf addComponents = compositeByteBuf.addComponents(true,cb1, cb2);
        System.out.println("compositeByteBuf == addComponents = " + (compositeByteBuf == addComponents));

        System.out.println("addComponents = " + addComponents);

    }
}
